package com.thread.threadlocal;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author: 一个小菜逼
 * @Date: 2020/4/3
 */
public class MyThreadLocalSimpleDateFormat {

    private static volatile //只创建了一个Threadlocal对象
            ThreadLocal<SimpleDateFormat> td=new ThreadLocal<SimpleDateFormat>();

    private static SimpleDateFormat getDateFormat() {
        SimpleDateFormat sdf=td.get();
        if(sdf==null) {
            sdf=new SimpleDateFormat("yyyy-MM-dd");
            td.set(sdf);
        }
        return sdf;
    }

    public static String format(Date date) {
        return getDateFormat().format(date);
    }

    public static Date parse(String dateStr) throws ParseException {
        return getDateFormat().parse(dateStr);
    }

    //这个主函数是测试用的，跟这个工具类没啥关系..
    public static void main(String[] args) throws Exception {
        //这个M得是大写（"yyyy-MM-dd"）
        //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

        //String date = sdf.format(new Date());
        //Date date2 = sdf.parse("2020-1-28 20:49:33");
        //System.out.println(date2);
        //System.out.println(date);

        String date = MyThreadLocalSimpleDateFormat.format(new Date());
        System.out.println(date);
        Date date2 = MyThreadLocalSimpleDateFormat.parse("2020-1-28 20:49:33");
        System.out.println(date2);
    }

}
